package list;

import java.util.Arrays;
public class MyArrayList {
    public int[] elem;
    public int usedSize;
    public static final int SIZE = 3;

    public MyArrayList() { //构造方法
        this.elem = new int[SIZE];
    }

    public void printElem() { //打印元素
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public int size() { // 获取顺序表长度
        return this.usedSize;
    }

    public boolean contains(int value) { //判断顺序表是否包含某个值
        for (int i = 0; i < this.usedSize; i++) {
            if (value == elem[i]) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int pos) { //获取pos位置元素
        checkIndex(pos);
        return elem[pos];
    }
    public int reIndex(int data){ //返回data元素的索引
        for (int i = 0; i < usedSize; i++) {
            if(this.elem[i] == data){
                return i;
            }
        }
        return -1;
    }
    public void add(int data) { //尾插元素
        if (isFull()) {
            this.elem = Arrays.copyOf(elem, 2 * this.elem.length);
        }
        this.elem[this.usedSize] = data;
        this.usedSize++;
    }
    public void checkIndex(int pos){ //检查位置合法性
        if(pos < 0 || pos > usedSize){
            throw new IndexOutOfException("位置有误");
        }
    }
    public void add(int pos, int data) { //在pos位置插入元素
        if(pos == usedSize) {
            add(data);
            return;
        }
        if (isFull()) {
            this.elem = Arrays.copyOf(elem, 2 * this.elem.length);
        }
        checkIndex(pos);
        for (int i = usedSize - 1; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        usedSize++;
    }

    public boolean isFull() { //判断顺序表是否已满
        return this.usedSize == SIZE;
    }
    public boolean remove(int key){ //删除第一次出现的关键字
        int index = reIndex(key);
        if(index == -1){
            throw new IndexOutOfException("位置有误");
        }else{
            for (int i = index; i < usedSize-1; i++) {
                this.elem[i] = this.elem[i+1];
            }
            usedSize--;
            elem[usedSize] = 0;
        }
        return true;
    }

    public static void main(String[] args) {
        MyArrayList myArrayList = new MyArrayList();
        myArrayList.add(5);
        myArrayList.add(4);
        myArrayList.add(3);
        myArrayList.add(6);
        myArrayList.printElem();
        myArrayList.add(0,10);
        myArrayList.remove(6);
        try {
            myArrayList.remove(7);
        } catch (IndexOutOfException e){
            e.printStackTrace();
        }
        myArrayList.printElem();
    }
}
